/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.zbxsoft.message.service.helper  
 */
package com.dwusoft.platform.template;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Locale;
import java.util.Map;

import org.apache.log4j.Logger;

import com.apache.uct.common.ToolsUtil;
import com.dwusoft.platform.template.method.FormatDateMethod;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * description:  模板操作辅助类
 * @author Hou Dayu 创建时间：2015-7-8  
 * 
 */
public class FreemarkerHelper {

	private Logger log = Logger.getLogger(FreemarkerHelper.class);
	private static FreemarkerHelper helper;

	private Configuration freemarker_cfg = null;

	private FreemarkerHelper() {
	}

	public static FreemarkerHelper instance() {
		if (null == helper) {
			helper = new FreemarkerHelper();
		}
		return helper;
	}

	public String getTemplateStr(String templateName, Map mapData) throws Exception {
		Template template = getFreeMarkerCFG().getTemplate(templateName);
		template.setEncoding("UTF-8");

		StringWriter stream = new StringWriter();
		template.process(mapData, stream);
		String sndRtn = stream.toString();//FreeMarkerTemplateUtils.processTemplateIntoString(template, mapData);
		return sndRtn;
	}

	/** 
	 * 获取freemarker的配置. freemarker本身支持classpath,目录和从ServletContext获取. 
	 */
	private Configuration getFreeMarkerCFG() {
		if (null == freemarker_cfg) {
			File templateFile = new File(ToolsUtil.getClassLoaderPath().replaceAll("WEB-INF/classes/", "") + "template");
			freemarker_cfg = new Configuration();
			try {
				freemarker_cfg.setDirectoryForTemplateLoading(templateFile);
				freemarker_cfg.setEncoding(Locale.CHINA, "UTF-8");
			} catch (IOException e) {
				log.error("Get tempalte error", e);
			}
			freemarker_cfg.setSharedVariable("timeStr", new FormatDateMethod());
		}
		return freemarker_cfg;
	}
}
